/**
 * Created with IntelliJ IDEA.
 * Description:
 * Us
 * er: WHY
 * Date: 2023-04-21
 * Time: 20:47
 */
//求正数数组的最小不可组成和（Java实现，01背包衍生问题）
public class Solution {
    public static int getFirstUnFormedNum(int[] arr) {
        // 1. 找到最大值和最小值
        int max = 0;
        int min = Integer.MAX_VALUE;
        for (int i = 0; i < arr.length; i++) {
            max += arr[i];
            if (min > arr[i]) {
                min = arr[i];
            }
        }

        // 2. 定义 dp 数组
        int[][] dp = new int[arr.length+1][max+1];
        // 初始化
        dp[1][1] = 1;

        // 3. 递推
        for (int i = 1; i <= arr.length; i++) {
            for (int j = 1; j <= max; j++) {
                // 小于情况下
                if (j < arr[i-1]) {
                    dp[i][j] = dp[i-1][j];
                }
                // 等于情况下
                else if (j == arr[i-1]) {
                    dp[i][j] = 1;
                }
                // 大于情况下
                else {
                    if (dp[i-1][j-arr[i-1]] == 1) {
                        dp[i][j] = 1;
                    }else if (dp[i-1][j] == 1) {
                        dp[i][j] = 1;
                    }
                    else {
                        dp[i][j] = 0;
                    }
                }
            }
        }

        // 查看二维数组
        for (int i = 0; i <= arr.length; i++) {
            for (int j = 0; j <= max; j++) {
                System.out.print(dp[i][j] + " ");
            }
            System.out.println();
        }

        // 4. 查询结果 结果在最后一行
        int index = arr.length;
        for (int i = min; i <= max; i++) {
            if (dp[index][i] != 1) {
                return i;
            }
        }
        return max+1;
    }

}
